﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using NetWing.Model;//系统所有的model 都在这个命名空间里，这个还是比较有好处的。
using NetWing.BPM.Core;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using NetWing.Common.Data;

namespace NetWing.BPM.Admin.mjprint
{
    public partial class tfsj : System.Web.UI.Page
    {
        public bool showprint = false;//显示打印按钮
        public string mainKeyId = "";
        public DataTable dtmain = null;
        public DataTable dtdetail = null;
        public decimal paytotal = 0;//结单时找补
        public string note = "";//备注
        public string hth = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            mainKeyId = Request["KeyId"];
            string sqlmain = "select * from MJOrder where KeyId=" + mainKeyId + "";
            dtmain = SqlEasy.ExecuteDataTable(sqlmain);
            string sqldetail = "select * from MJOrderDetail where MJOrderid=" + mainKeyId + " order by KeyId asc";
            dtdetail = SqlEasy.ExecuteDataTable(sqldetail);
            DataRow drm = dtmain.Rows[0];
            if (drm["orderstatus"].ToString()=="-1")//如果是已经结算的订单则不显示
            {
                this.opt.Visible = false;
                showprint = true;//显示打印按钮
                hth = drm["ednumber"].ToString();
            }
            

        }
        /// <summary>
        /// 得到科目类型 连续计费返回0 一次计费返回1
        /// </summary>
        public int[] getSubjectType(string subjectid) {
            int[] k = {0,0};//第一个0代表持续性收费，第二个0代表不可退
            string sqltemp = "select * from MJaccountingSubjects where keyid="+subjectid+"";
            DataRow drtemp=SqlEasy.ExecuteDataRow(sqltemp);
            k[0] = int.Parse(drtemp["theonce"].ToString());//代表是否是持续性收费
            k[1] = int.Parse(drtemp["istui"].ToString());//0代表不可退1代表可以退
            return k;
        }

        protected void customsure_Click(object sender, EventArgs e)
        {
            //先得到财务单号
            string ftype = "支出";
            int mainInsertedId =0;
            string edNumber = common.mjcommon.getedNumber("F");
            string newnote = Request["note"];//所有备注
            decimal newpaytotal = decimal.Parse(Request["paytotal"].ToString());
            string account = Request["account"].ToString();//入款银行
            int accountid = int.Parse(Request["accountid"].ToString());//入款银行id
            string contact = Request["contact"];//经手人
            int contactid = int.Parse(Request["contactid"].ToString());//经手人id
            decimal total = decimal.Parse(Request["total"].ToString());//合计金额
            decimal payment = decimal.Parse(Request["payment"].ToString());//实付金额

            string tuiserviceIds = Request["tuiserviceId"];//退的所有ID
            string tuinotes = Request["tuinote"];
            string tuimoneys = Request["tuimoney"];
            string[] tuiserviceIdsArr = null;
            if (!string.IsNullOrEmpty(tuiserviceIds))//如果应该退的id不为空
            {
                tuiserviceIdsArr = tuiserviceIds.Split(',');
            }

            //得到科目datatable 以便查询用 减少读数据库次数
            DataTable subjectDt = SqlEasy.ExecuteDataTable("select * from MJaccountingSubjects");



            //从主表里得到相关变量
            DataRow dr = dtmain.Rows[0];//只可能有一行

         
            //财务主表处理 方便以后财务统计s
            MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
            fmainModel.account = account;//账号
            fmainModel.accountid = accountid;//账号ID
            fmainModel.add_time = DateTime.Now;
            fmainModel.contact = contact;//经手人
            fmainModel.contactid = contactid;//经手人id
            fmainModel.dep = "";
            fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
            fmainModel.edNumber = edNumber;
            fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
            fmainModel.unit = dr["users"].ToString();//用户
            fmainModel.unitid = int.Parse(dr["usersid"].ToString());//用户ID
            fmainModel.note = newnote;
            fmainModel.payment = payment;
            fmainModel.total = total;
            fmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
            fmainModel.operate = SysVisitor.Instance.cookiesUserName;
            fmainModel.roomid = int.Parse(dr["roomid"].ToString());//房间id
            fmainModel.roomno = dr["roomno"].ToString();//房间号

            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                mainInsertedId = DbUtils.tranInsert(fmainModel, tran);//往主表插入一条

                #region 写财务明细表
                if (tuiserviceIdsArr==null)//如果没有退的
                {
                    MJFinanceDetailModel detailModel = new MJFinanceDetailModel();//初始化财务明细表模型
                    if (fmainModel.payment >= 0)
                    {
                        ftype = "收入";
                    }
                    detailModel.edNumber = edNumber;//订单号赋值
                    detailModel.financeId = mainInsertedId;//父子表关联
                    detailModel.add_time = DateTime.Now;
                    detailModel.up_time = DateTime.Now;
                    detailModel.ftype = ftype;//收支类型
                    detailModel.subject = "订单结算";
                    detailModel.subjectid = 0;//结算统一ID是0
                    detailModel.sumMoney = payment;
                    detailModel.dep = "";
                    detailModel.note = newnote;//备注信息
                    detailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                    detailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                    detailModel.roomid= int.Parse(dr["roomid"].ToString());//房间id
                    detailModel.roomno= dr["roomno"].ToString();//房间号
                    DbUtils.tranInsert(detailModel, tran);//执行写入明细表
                }
                else//如果有一个退的和多个退的
                {
                    for (int i = 0; i <tuiserviceIdsArr.Length; i++)
                    {
                        DataRow odr= subjectDt.Select("KeyId=" + tuiserviceIdsArr[i] + "")[0];//先得到原来的科目行
                        DataRow tdr= subjectDt.Select("KeyId=" + odr["reverseSubjects"] + "")[0];//得到退id和退科目
                        MJFinanceDetailModel detailModel = new MJFinanceDetailModel();//初始化财务明细表模型
                        //if (fmainModel.payment >= 0)
                        if (decimal.Parse(tuimoneys.Split(',')[i]) >= 0)//大于0是收入小于0是支出
                        {
                            ftype = "收入";
                            detailModel.subject = odr["subjectName"].ToString();
                            detailModel.subjectid = int.Parse(odr["KeyId"].ToString());//如果是正数则说明是补费用 延续用原来的科目
                        }
                        else//如果小于0则显示反方（退的科目）
                        {
                            ftype = "支出";
                            detailModel.subject = tdr["subjectName"].ToString();
                            detailModel.subjectid = int.Parse(tdr["KeyId"].ToString());//结算统一ID是0
                        }
                        detailModel.edNumber = edNumber;//订单号赋值
                        detailModel.financeId = mainInsertedId;//父子表关联
                        detailModel.add_time = DateTime.Now;
                        detailModel.up_time = DateTime.Now;
                        detailModel.ftype = ftype;//收支类型
                        detailModel.sumMoney = decimal.Parse(tuimoneys.Split(',')[i]);
                        detailModel.dep = "";
                        detailModel.note = tuinotes.Split(',')[i];//备注信息
                        detailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        detailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModel.roomid = int.Parse(dr["roomid"].ToString());//房间id
                        detailModel.roomno = dr["roomno"].ToString();//房间号
                        DbUtils.tranInsert(detailModel, tran);//执行写入明细表
                    }
                }
                #endregion





                //事务的方法更新银行余额
                int c = DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + fmainModel.payment + " where KeyId=" + fmainModel.accountid + "", tran);
                //给订单主表结单 订单状态0正常-1结单
                string omainsql = "update MJOrder set orderstatus=-1 where keyid="+mainKeyId+"";
                DbUtils.tranExecuteNonQuery(omainsql,tran);
                //给订单明细表结单
                string odetailsql = "update MJOrderDetail set orderstatus=-1   where MJOrderid=" + mainKeyId+"";
                DbUtils.tranExecuteNonQuery(odetailsql, tran);
                //清空房间使用者信息
                //string clearroomsql = "update MJRooms set userids=null,usernames=null,usermobiles=null where roomnumber='"+dr["roomno"]+"'";
                string clearroomsql= "update MJRooms set userids = null, usernames = null, usermobiles = null, state = '空闲', add_time = null, exp_time = null, orderstart_time = null, orderend_time = null, zuqi = null, jzrs = null, OrderId = null, rzl = null, paytype = null, nextpaydate = null  where roomnumber='" + dr["roomno"] + "'";
                DbUtils.tranExecuteNonQuery(clearroomsql, tran);

                tran.Commit();//提交执行事务
                showprint = true;//显示打印菜单
               

            }
            catch (Exception err)
            {
                tran.Rollback();//错误！事务回滚！
                //context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                Response.Write(err.ToString());
                throw;
            }

            Response.Redirect(Request.Url.ToString());//刷新本页


        }
    }
}